package com.zhongkai.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PermissionFilter extends HttpServlet implements Filter {

	@Override
	public void doFilter(ServletRequest rq, ServletResponse rs,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request=(HttpServletRequest)rq;
		HttpServletResponse response=(HttpServletResponse)rs;
		HttpSession session = request.getSession();
		String path=request.getContextPath();
		String actionUrl=request.getSession().getAttribute("actionUrl").toString();
		String url=request.getServletPath();
		Pattern pattern=Pattern.compile(actionUrl);
		Matcher matcher=pattern.matcher(url);
		if(matcher.matches()){
			chain.doFilter(request, response);
		}
		else{
			PrintWriter out=((HttpServletResponse) response).getWriter();
			out.println("<script type='text/javascript' language='javascript'>alert('权限不足，无权访问！');parent.location.href='"+path+"/system/index.jsp'</script>");
			out.flush();
			out.close();
			return;
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

}
